import styles from "@styles/personal.module.less";
import React, { useRef } from "react";
import { SlideRef } from "@shared/slide";
import { useUploadMutation } from "@service/userEndpoints";
import toast from "react-hot-toast";

interface Props {
  // slide 组件实例对象, 因为当前组件将来要关闭弹窗
  // 所以当前组件要接收弹层对象实例
  slideRef: React.RefObject<SlideRef | null>;
}

export default function UpdateAvatar({ slideRef }: Props) {
  // 用于存储文件选择控件对象
  const fileRef = useRef<null | HTMLInputElement>(null);
  // 获取上传头像的方法
  const [upload] = useUploadMutation();
  const trigger = (mark: "take" | "select") => {
    if (mark === "take") {
      // 开启前置摄像头
      fileRef.current?.setAttribute("capture", "user");
    } else if (mark === "select") {
      fileRef.current?.removeAttribute("capture");
    }
    // 打开文件选择控件
    fileRef.current?.click();
  };
  // 上传头像
  const uploadAvatar = (event: React.ChangeEvent<HTMLInputElement>) => {
    // 文件列表
    const files = event.target.files;
    if (files === null) return;
    const file = files[0];
    // 创建表单对象
    const formData = new FormData();
    formData.append("photo", file);
    // 发送请求上传头像
    upload(formData)
      .unwrap()
      .then(() => {
        toast.success("头像更新成功");
        slideRef.current?.close();
      })
      .catch((error) => {
        toast.error("头像更新失败");
      });
  };

  return (
    <ul className={styles.list}>
      <li onClick={() => trigger("take")}>拍照</li>
      <li onClick={() => trigger("select")}>选择照片</li>
      <li onClick={() => slideRef.current?.close()}>取消</li>
      <input
        ref={fileRef}
        type="file"
        accept="image/png, image/gif, image/jpeg"
        style={{ display: "none" }}
        onChange={uploadAvatar}
      />
    </ul>
  );
}
